<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="日期" prop="date">
        <el-date-picker
            v-model="queryParams.date"
            type="date"
            placeholder="请选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
            style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="策略实例名称" prop="strategyInstance">
        <el-input v-model="queryParams.strategyInstance" placeholder="请输入策略实例名称" clearable style="width: 200px"
                  @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
                   v-hasPermi="['kylin:futureStrategyPosition:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['kylin:futureStrategyPosition:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['kylin:futureStrategyPosition:remove']">
          删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="strategyPositionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="日期" align="center" prop="date" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="策略实例名称" align="center" prop="strategyInstance" width="200"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="仓位" align="center" prop="position" width="100" :show-overflow-tooltip="true"/>
      <el-table-column label="多仓" align="center" prop="longPosition" width="100" :show-overflow-tooltip="true"/>
      <el-table-column label="空仓" align="center" prop="shortPosition" width="100" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['kylin:futureStrategyPosition:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['kylin:futureStrategyPosition:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改期货策略仓位对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="strategyPositionRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="日期" prop="date">
          <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="请选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="策略实例名称" prop="strategyInstance">
          <el-input v-model="form.strategyInstance" placeholder="请输入策略实例名称"/>
        </el-form-item>
        <el-form-item label="仓位" prop="position">
          <el-input v-model.number="form.position" placeholder="请输入仓位"/>
        </el-form-item>
        <el-form-item label="多仓" prop="longPosition">
          <el-input v-model.number="form.longPosition" placeholder="请输入多仓"/>
        </el-form-item>
        <el-form-item label="空仓" prop="shortPosition">
          <el-input v-model.number="form.shortPosition" placeholder="请输入空仓"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FutureStrategyPosition">
import {
  listFutureStrategyPosition,
  getFutureStrategyPosition,
  addFutureStrategyPosition,
  updateFutureStrategyPosition,
  delFutureStrategyPosition
} from '@/api/kylin/futureStrategyPosition';
import {ref, reactive, onMounted, toRefs} from 'vue';

const {proxy} = getCurrentInstance();

const strategyPositionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    date: undefined,
    strategyInstance: undefined
  },
  rules: {
    date: [
      {required: true, message: '日期不能为空', trigger: 'blur'}
    ],
    strategyInstance: [
      {required: true, message: '策略实例名称不能为空', trigger: 'blur'},
      {min: 1, max: 100, message: '策略实例名称长度不能超过100个字符', trigger: 'blur'}
    ],
    position: [
      {required: true, message: '仓位不能为空', trigger: 'blur'},
      {type: 'number', message: '仓位必须为数字值', trigger: 'blur'}
    ],
    longPosition: [
      {required: true, message: '多仓不能为空', trigger: 'blur'},
      {type: 'number', message: '多仓必须为数字值', trigger: 'blur'}
    ],
    shortPosition: [
      {required: true, message: '空仓不能为空', trigger: 'blur'},
      {type: 'number', message: '空仓必须为数字值', trigger: 'blur'}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询期货策略仓位列表 */
function getList() {
  loading.value = true;
  listFutureStrategyPosition(queryParams.value).then(response => {
    // 添加调试日志，打印完整的response结构
    console.log('完整响应数据:', response);

    // 检查response结构并正确赋值
    // 这里可能需要根据实际返回的数据结构进行调整
    if (response.rows && response.total) {
      // 如果数据直接在response中
      strategyPositionList.value = response.rows;
      total.value = response.total;
    } else if (response.data) {
      // 如果数据在response.data中
      const data = response.data || {rows: [], total: 0};
      strategyPositionList.value = data.rows || [];
      total.value = data.total || 0;
    } else {
      // 默认空数据
      strategyPositionList.value = [];
      total.value = 0;
    }

    loading.value = false;
  }).catch(error => {
    console.error('查询数据失败:', error);
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {};
  proxy.resetForm('strategyPositionRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加期货策略仓位';
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const positionId = row.id || ids.value;
  getFutureStrategyPosition(positionId).then(response => {
    // 添加调试日志，打印完整的响应数据
    console.log('获取单个期货策略仓位数据:', response);

    // 检查响应数据结构并正确赋值，确保策略实例名称、多仓和空仓的值能被正确获取
    if (response && response.data) {
      // 如果数据在response.data中
      form.value.id = response.data.id;
      form.value.date = response.data.date;
      form.value.strategyInstance = response.data.strategy_instance;
      form.value.position = response.data.position;
      form.value.longPosition = response.data.long_position;
      form.value.shortPosition = response.data.short_position;
    }
    open.value = true;
    title.value = '修改期货策略仓位';
  }).catch(error => {
    console.error('获取单个期货策略仓位数据失败:', error);
  });
}

/** 提交按钮 */
function submitForm() {
  // 确保表单数据完整性
  if (!form.value.strategyInstance) {
    form.value.strategyInstance = '';
  }
  if (form.value.longPosition === undefined || form.value.longPosition === null) {
    form.value.longPosition = 0;
  }
  if (form.value.shortPosition === undefined || form.value.shortPosition === null) {
    form.value.shortPosition = 0;
  }
  if (form.value.position === undefined || form.value.position === null) {
    form.value.position = 0;
  }

  proxy.$refs['strategyPositionRef'].validate(valid => {
    if (valid) {
      if (form.value.id) {
        updateFutureStrategyPosition(form.value.id, form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        }).catch(error => {
          console.error('修改失败:', error);
          proxy.$modal.msgError('修改失败，请重试');
        });
      } else {
        addFutureStrategyPosition(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        }).catch(error => {
          console.error('新增失败:', error);
          proxy.$modal.msgError('新增失败，请重试');
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const positionIds = row.id ? [row.id] : ids.value;
  proxy.$modal.confirm('是否确认删除期货策略仓位？').then(() => {
    return delFutureStrategyPosition(positionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess('删除成功');
  }).catch(() => {
  });
}

// 组件初始化查询
onMounted(() => {
  getList();
});
</script>